package fun.sboy.headacheMemo.interceptor;


import fun.sboy.headacheMemo.commons.lang.TokenNotFindException;
import fun.sboy.headacheMemo.controller.LoginController;
import fun.sboy.headacheMemo.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            if (token == null || "".equals(token)) {
                throw new TokenNotFindException("当前未登录，Token不存在！");
            }
            String uid = TokenUtil.parseToken(token).getSubject();
            RequestContextHolder.currentRequestAttributes().setAttribute("currentUser", uid, RequestAttributes.SCOPE_REQUEST);
            String redisToken = (String) redisTemplate.opsForValue().get(LoginController.REDIS_LOGIN_PREFIX + uid);
            System.out.printf("登录用户：%s\n", uid);
            if (redisToken == null) {
                throw new TokenNotFindException("登录过期，请重新登录！redis中Token过期");
            }
        } catch (IllegalStateException e) {
            throw new RuntimeException("登录过期，请重新登录！");
        }
        return true;
    }

}
